import requests, re, random, threading


class phpwindPost():
    # 定义baseUrl
    # 使用requests库中的session类维护cookie, 建立长久的会话
    def __init__(self):
        self.baseUrl = 'http://localhost:8088/phpwind/'
        self.s = requests.session()

    def sendGet(self, url):
        r = self.s.get(url)
        return r

    def sendPost(self, url, data, file=None):
        r = self.s.post(url, data=data, files=file)
        return r

    # 获取请求的响应
    def getResp(self, r):
        r.encoding = 'utf-8'
        return r.text

    # 查找响应当中的内容，通过字符串处理方法或者正则表达式来完成
    def searchResp(self, pattern, content):
        rr = re.compile(pattern)
        matchStr = rr.findall(content)
        return matchStr

    def logIn(self):
        url = 'http://localhost:8088/phpwind/login.php?'
        data = {"pwuser": 'admin', "pwpwd": 'admin', "cktime": "31536000", 'jumpurl': 'http://localhost:8088/phpwind/',
                'step': 2, 'lgt': 0, 'hideid': 0}
        r = self.sendPost(url, data)
        resp = self.getResp(r)
        return resp

    def getVerifyCode(self):
        self.logIn()
        r = self.sendGet('http://localhost:8088/phpwind/post.php?fid=2')
        resp = self.getResp(r)
        pattern = 'name="verify" value="(.*)"'
        verifyCode = self.searchResp(pattern, resp)
        return verifyCode

    def getFids(self):
        url = 'http://localhost:8088/phpwind/'
        r = self.sendGet('http://localhost:8088/phpwind/')
        resp = self.getResp(r)
        pattern = '<tr class="tr3 f_one" id="fid_(.*)">'
        fids = self.searchResp(pattern, resp)
        return fids

    def doPost(self):
        self.logIn()
        verifyCode = self.getVerifyCode()
        fids = self.getFids()
        fid = random.choice(fids)
        url = 'http://localhost:8088/phpwind/post.php?'
        data = {'magicname': '', 'magicid': '', 'verify': verifyCode, 'atc_title': 'phpwind title', 'atc_iconid': 0,
                'atc_content': 'python content', 'atc_autourl': 1, 'atc_usesign': 1, 'atc_convert': 1, 'digest': 0,
                'topped': 0, 'atc_rvrc': 0, 'atc_enhidetype': 'rvrc', 'atc_money': 0, 'atc_credittype': 'money',
                'att_special1': 0, 'att_ctype1': 'money', 'atc_needrvrc1': 0, 'step': 2, 'pid': '', 'action': 'new',
                'fid': fid, 'tid': '', 'article,': 0, 'special': 0}
        file = {'attachment_1': open('testdemo.txt', 'rb')}
        r = self.sendPost(url, data, file)
        resp = self.getResp(r)
        return resp


if __name__ == '__main__':
    p = phpwindPost()
    print(p.doPost())

    # threads = []
    # for i in range(0,5):
    #     t = threading.Thread(target=p.doPost, args='') #t = threading.Thread(target=p.doPost, args=())
    #     threads.append(t)
    # for t in threads:
    #     t.start()
    # for t in threads:
    #     t.join()
